<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--部门数据-->
            <el-col :span="4" :xs="24">
                <div class="head-container">
                    <el-input
                        v-model="deptName"
                        placeholder="请输入部门名称"
                        clearable
                        size="small"
                        prefix-icon="el-icon-search"
                        style="margin-bottom: 20px"
                    />
                </div>
                <div class="head-container">
                    <el-tree
                        :data="deptOptions"
                        :props="defaultProps"
                        :expand-on-click-node="false"
                        :filter-node-method="filterNode"
                        ref="tree"
                        default-expand-all
                        highlight-current
                        @node-click="handleNodeClick"
                    />
                </div>
            </el-col>
            <!--考勤配置信息-->
            <el-col :span="20" :xs="24">
                <el-row class="mb8">
                    <el-alert
                        title="考勤规则优先用自己单位设置的规则，如自己组织没有设置，则使用父级最近的组织所设置的规则。"
                        type="success"
                        :closable="false"
                        style="padding: 20px"
                    ></el-alert>
                </el-row>
                <TableCard>
                    <el-row :gutter="10" class="mb8">
                        <el-col :span="1.5">
                            <el-button
                                type="danger"
                                plain
                                icon="el-icon-delete"
                                size="mini"
                                @click="handleDelete"
                                v-hasPermi="[
                                    'hrm:workAttendancesConfig:remove',
                                ]"
                                v-if="form.ifExtends == 'N'"
                            >
                                删除配置
                            </el-button>
                        </el-col>
                        <el-col :span="1.5">
                            <el-button
                                type="primary"
                                plain
                                icon="el-icon-plus"
                                size="mini"
                                @click="submitForm"
                                v-hasPermi="['hrm:workAttendancesConfig:add']"
                            >
                                保存
                            </el-button>
                        </el-col>
                    </el-row>

                    <el-form
                        ref="form"
                        :model="form"
                        :rules="rules"
                        label-width="120px"
                    >
                        <el-row>
                            <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
                                <el-form-item label="部门名称" prop="deptName">
                                    <el-input
                                        v-model="form.deptName"
                                        placeholder="请点击左侧结构树"
                                        disabled
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
                                <el-form-item label="经度" prop="coordinateX">
                                    <el-input
                                        v-model="form.coordinateX"
                                        placeholder="请点击地图选择打卡地点"
                                        disabled
                                    />
                                </el-form-item>
                            </el-col>
                            <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
                                <el-form-item label="纬度" prop="coordinateY">
                                    <el-input
                                        v-model="form.coordinateY"
                                        placeholder="请点击地图选择打卡地点"
                                        disabled
                                    />
                                </el-form-item>
                            </el-col>
                            <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
                                <el-form-item label="打卡半径" prop="radius">
                                    <el-input
                                        v-model="form.radius"
                                        placeholder="请输入打卡半径"
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
                                <el-form-item label="是否考核" prop="ifExamine">
                                    <el-select
                                        v-model="form.ifExamine"
                                        placeholder="请选择是否考核"
                                    >
                                        <el-option
                                            v-for="dict in dict.type.sys_yes_no"
                                            :key="dict.value"
                                            :label="dict.label"
                                            :value="dict.value"
                                        ></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
                                <el-form-item
                                    label="上班打卡时间"
                                    prop="startWorkTime"
                                >
                                    <el-time-picker
                                        placeholder="请选择上班打卡时间"
                                        clearable
                                        :picker-options="{ format: 'HH:mm' }"
                                        value-format="HH:mm"
                                        v-model="form.startWorkTime"
                                    >
                                    </el-time-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
                                <el-form-item
                                    label="下班打卡时间"
                                    prop="finishWorkTime"
                                >
                                    <el-time-picker
                                        placeholder="请选择下班打卡时间"
                                        clearable
                                        :picker-options="{ format: 'HH:mm' }"
                                        value-format="HH:mm"
                                        v-model="form.finishWorkTime"
                                    >
                                    </el-time-picker>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col
                                :xs="8"
                                :sm="8"
                                :md="8"
                                :lg="8"
                                :xl="8"
                                v-if="form.ifExamine == 'Y'"
                            >
                                <el-form-item
                                    label="允许迟到天数/月"
                                    prop="minLateDays"
                                >
                                    <el-input
                                        v-model="form.minLateDays"
                                        placeholder="请输入每月允许迟到天数"
                                    />
                                </el-form-item>
                            </el-col>
                            <el-col
                                :xs="8"
                                :sm="8"
                                :md="8"
                                :lg="8"
                                :xl="8"
                                v-if="form.ifExamine == 'Y'"
                            >
                                <el-form-item
                                    label="允许早退天/月"
                                    prop="minLeaveEarlyDays"
                                >
                                    <el-input
                                        v-model="form.minLeaveEarlyDays"
                                        placeholder="请输入每月允许早退天数"
                                    />
                                </el-form-item>
                            </el-col>
                            <el-col
                                :xs="8"
                                :sm="8"
                                :md="8"
                                :lg="8"
                                :xl="8"
                                v-if="form.ifExamine == 'Y'"
                            >
                                <el-form-item
                                    label="允许缺卡次数/月"
                                    prop="minLackTimes"
                                >
                                    <el-input
                                        v-model="form.minLackTimes"
                                        placeholder="请输入每月允许缺卡次数"
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col
                                :xs="8"
                                :sm="8"
                                :md="8"
                                :lg="8"
                                :xl="8"
                                v-if="form.ifExamine == 'Y'"
                            >
                                <el-form-item
                                    label="迟到罚款金额/天"
                                    prop="lateFine"
                                >
                                    <el-input
                                        v-model="form.lateFine"
                                        placeholder="请输入迟到罚款金额/天"
                                    />
                                </el-form-item>
                            </el-col>
                            <el-col
                                :xs="8"
                                :sm="8"
                                :md="8"
                                :lg="8"
                                :xl="8"
                                v-if="form.ifExamine == 'Y'"
                            >
                                <el-form-item
                                    label="早退罚款金额/天"
                                    prop="leaveEarlyFine"
                                >
                                    <el-input
                                        v-model="form.leaveEarlyFine"
                                        placeholder="请输入早退罚款金额/天"
                                    />
                                </el-form-item>
                            </el-col>
                            <el-col
                                :xs="8"
                                :sm="8"
                                :md="8"
                                :lg="8"
                                :xl="8"
                                v-if="form.ifExamine == 'Y'"
                            >
                                <el-form-item
                                    label="缺卡罚款金额/次"
                                    prop="lackFine"
                                >
                                    <el-input
                                        v-model="form.lackFine"
                                        placeholder="请输入每月允许迟到天数/次"
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-form-item label="备注" prop="remark">
                                <el-input
                                    v-model="form.remark"
                                    type="textarea"
                                    :rows="5"
                                    placeholder="请输入内容"
                                />
                            </el-form-item>
                        </el-row>
                    </el-form>

                    <!-- 地图组件  -->
                    <div class="mapRow">
                        <div id="mapContainer"></div>
                        <!-- 查询输入条 -->
                        <el-row class="seachAddress">
                            <el-input
                                id="tipinput"
                                v-model="mapAddress"
                                placeholder="请输入地址进行查询"
                                @input="searchKeyWord"
                            />
                        </el-row>
                        <!-- 查询结果 -->
                        <div
                            class="map_search_result"
                            v-show="showSearchResult"
                        >
                            <div
                                class="row"
                                @click="markerResult(item)"
                                v-for="(item, index) in poiList"
                                :key="index"
                            >
                                {{ item.name }}
                            </div>
                        </div>
                    </div>
                </TableCard>
            </el-col>
        </el-row>

        <!-- 添加或修改考勤配置对话框 -->
        <!--        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>-->

        <!--            </el-form>-->
        <!--            <div slot="footer" class="dialog-footer">-->
        <!--                <el-button type="primary" @click="submitForm">确 定</el-button>-->
        <!--                <el-button @click="cancel">取 消</el-button>-->
        <!--            </div>-->
        <!--        </el-dialog>-->
    </div>
</template>

<script>
import {
    addWorkAttendancesConfig,
    delWorkAttendancesConfig,
    selectHrmWorkAttendancesConfigByDeptId,
    updateWorkAttendancesConfig,
} from "@/api/hrm/workAttendancesConfig";
import { treeselect } from "@/api/system/dept";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import AMapLoader from "@amap/amap-jsapi-loader";
import MapContainer from "@/views/hrm/workAttendancesConfig/MapContainer";

window._AMapSecurityConfig = {
    securityJsCode: "7a2fbce5a795a9a2f9215c3c2ddb4d1b", //你的秘钥
};

export default {
    name: "WorkAttendancesConfig",
    dicts: ["sys_yes_no"],
    components: { MapContainer },
    data() {
        return {
            showSearchResult: true,
            placeSearchComponent: null,
            autoCompleteComponent: null,
            geocoder: null,
            mapAddress: "",
            poiList: [],
            // 部门名称
            deptId: "",
            map: null,
            deptName: "",
            // 部门树选项
            deptOptions: [],
            defaultProps: {
                children: "children",
                label: "label",
            },
            // 表单参数
            form: {
                //半径
                radius: 300,
            },
            // 表单校验
            rules: {
                coordinateX: [
                    {
                        required: true,
                        message: "经度不能为空",
                        trigger: "blur",
                    },
                ],
                coordinateY: [
                    {
                        required: true,
                        message: "纬度不能为空",
                        trigger: "blur",
                    },
                ],
                radius: [
                    {
                        required: true,
                        message: "打卡半径不能为空",
                        trigger: "blur",
                    },
                ],
                ifExamine: [
                    {
                        required: true,
                        message: "是否需要考核不能为空",
                        trigger: "blur",
                    },
                ],
                finishWorkTime: [
                    {
                        required: true,
                        message: "下班打卡时间不能为空",
                        trigger: "blur",
                    },
                ],
                startWorkTime: [
                    {
                        required: true,
                        message: "上班打卡时间不能为空",
                        trigger: "blur",
                    },
                ],
            },
        };
    },
    created() {
        this.getTreeselect();
    },
    mounted() {
        this.initAMap();
    },
    unmounted() {
        this.map?.destroy();
    },
    methods: {
        /** 查询部门下拉树结构 */
        getTreeselect() {
            treeselect().then((response) => {
                this.deptOptions = response.data;
            });
        },
        // 筛选节点
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        // 节点单击事件
        handleNodeClick(data) {
            this.reset();
            this.deptId = data.id;
            this.deptName = data.label;
            this.handleUpdate();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                deptName: null,
                coordinateX: null,
                coordinateY: null,
                radius: null,
                ifExamine: null,
                minLateDays: null,
                minLeaveEarlyDays: null,
                minAbsenteeismDays: null,
                startWorkTime: null,
                finishWorkTime: null,
                absenteeismHours: null,
                lateFine: null,
                leaveEarlyFine: null,
                absenteeismFine: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null,
                tenantId: null,
            };
            this.resetForm("form");
        },
        /** 修改按钮操作 */
        handleUpdate() {
            selectHrmWorkAttendancesConfigByDeptId(this.deptId).then(
                (response) => {
                    if (200 == response.code) {
                        if (!response.data) {
                            this.form.deptId = this.deptId;
                            this.form.deptName = this.deptName;
                        } else {
                            this.form = response.data;
                            if ("Y" == this.form.ifExtends) {
                                //继承
                                this.form.deptName =
                                    this.form.deptName +
                                    "（继承自：" +
                                    this.form.extendsDeptName +
                                    "）";
                            }
                            this.mapShowCircle(
                                this.form.coordinateX,
                                this.form.coordinateY
                            );
                        }
                    }
                }
            );
        },
        /** 提交按钮 */
        submitForm() {
            if (!this.form.deptId) {
                this.$modal.msgError("请选择需要配置的部门");
                return;
            }

            if (this.form.ifExtends == "Y") {
                this.$modal
                    .confirm(
                        "该部门目前的配置为继承自父级单位，您是否想讲该配置保存为该单位自身的配置？"
                    )
                    .then(() => {
                        this.form.id = null;
                        this.form.deptId = this.deptId;
                        this.doSubmit();
                    });
            } else {
                this.doSubmit();
            }
        },
        doSubmit() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.id != null) {
                        updateWorkAttendancesConfig(this.form).then(
                            (response) => {
                                this.$modal.msgSuccess("修改成功");
                            }
                        );
                    } else {
                        addWorkAttendancesConfig(this.form).then((response) => {
                            this.$modal.msgSuccess("新增成功");
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal
                .confirm('是否确认删除考勤配置编号为"' + ids + '"的数据项？')
                .then(() => {
                    return delWorkAttendancesConfig(ids);
                })
                .then(() => {
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => {});
        },

        initAMap() {
            AMapLoader.load({
                key: "653c4c81c212e962e26cc788725c6794", // 申请好的Web端开发者Key，首次调用 load 时必填
                version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: [
                    "AMap.ToolBar",
                    "AMap.Scale",
                    "AMap.Geolocation",
                    "AMap.PlaceSearch",
                    "AMap.AutoComplete",
                    "AMap.Geocoder",
                    "AMap.CitySearch",
                ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            })
                .then((AMap) => {
                    this.map = new AMap.Map("mapContainer", {
                        //设置地图容器id
                        viewMode: "3D", //是否为3D地图模式
                        zoom: 12, //初始化地图级别
                    });
                    this.handleClick(AMap); //地图选点
                    this.map.addControl(new AMap.Scale()); // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
                    this.map.addControl(new AMap.ToolBar()); //在图面添加鹰眼控件，在地图右下角显示地图的缩略图
                    this.geocoder = new AMap.Geocoder();
                    this.mapSearchInit();
                })
                .catch((e) => {
                    console.log(e);
                });
        },

        //根据坐标显示圆圈和标记
        mapShowCircle(lng, lat) {
            let marker = new AMap.Marker({
                position: new AMap.LngLat(lng, lat),
            });
            this.map.clearMap(); // 清除所有覆盖物（点标志）
            this.map.add(marker); // 添加点标志
            let lnglat = [lng, lat];

            //显示圆圈
            var circle = new AMap.Circle({
                center: lnglat,
                radius: this.form.radius, //半径
                borderWeight: 3,
                strokeColor: "#FF33FF",
                strokeWeight: 6,
                strokeOpacity: 0.2,
                fillOpacity: 0.4,
                strokeStyle: "dashed",
                strokeDasharray: [10, 10],
                // 线样式还支持 'dashed'
                fillColor: "#1791fc",
                zIndex: 50,
            });
            this.map.add(circle);
            this.map.setFitView([circle]);

            console.log("半径：" + this.form.radius);

            // 绑定经纬度
            this.form.coordinateX = lng;
            // this.$set(this.form, 'coordinateX', lng);
            this.form.coordinateY = lat;
            this.$forceUpdate();

            console.log("经度：" + JSON.stringify(this.form));

            //显示位置
            // this.geocoder.getAddress(lnglat, (status, result)=> {
            //     if (status === 'complete' && result.regeocode) {
            //         this.address = result.regeocode.formattedAddress;
            //         this.showInfoWindow(marker);//自定义信息窗体
            //         let thisPosition = {
            //             address: this.address,
            //             lng: lng,
            //             lat: lat
            //         };
            //         this.$emit("select",thisPosition) //返回给父组件
            //     } else {
            //         this.$message.error('根据经纬度查询地址失败')
            //     }
            // })
        },
        //点击地图获取地理位置
        handleClick() {
            this.map.on("click", (e) => {
                let lng = e.lnglat.lng;
                let lat = e.lnglat.lat;
                //根据坐标显示圆圈和标记
                this.mapShowCircle(lng, lat);
            });
        },
        /** 初始化查询 */
        mapSearchInit() {
            let autoOptions = {
                input: "tipInput",
            };
            let autoCompleteComponent = new AMap.Autocomplete(autoOptions);
            this.autoCompleteComponent = autoCompleteComponent;
            // 注册placeSearch组件
            let PlaceSearchOptions = {
                //设置PlaceSearch属性
                city: "", //城市
                type: "", //数据类别
                pageSize: 210, //每页结果数,默认10
                pageIndex: 1, //请求页码，默认1
                extensions: "base", //返回信息详略，默认为base（基本信息）
            };
            this.placeSearchComponent = new AMap.PlaceSearch(
                PlaceSearchOptions
            );
        },
        //根据输入内容查询
        searchKeyWord() {
            debugger;
            this.placeSearchComponent.search(
                this.mapAddress,
                (status, result) => {
                    if (status === "complete" && result.info === "OK") {
                        console.log(this.showsearchResult);
                        this.showsearchResult = true;
                        this.poiList = result.poiList.pois;
                        this.$forceUpdate();
                    } else {
                        this.showsearchResult = true;
                        this.poiList = [];
                        this.$message({
                            message: "没有查到结果",
                            type: "warning",
                        });
                    }
                }
            );
        },
        //选择查询的内容
        markerResult(data) {
            this.poiList = [];
            this.showsearchResult = false;
            this.address = data.name;
            var marker = new AMap.Marker({
                position: [
                    Number(data.location.lng),
                    Number(data.location.lat),
                ],
            });
            this.map.clearMap(); // 清除所有覆盖物（点标志）
            this.map.add(marker); // 添加点标志
            this.showInfoWindow(marker);
            setTimeout(() => {
                this.map.setCenter(data.location);
                this.map.setZoom(15);
            }, 50);
            let thisPosition = {
                address: this.address,
                lng: data.location.lng,
                lat: data.location.lat,
            };
            this.$emit("select", thisPosition);
        },
        //自定义信息窗体
        showInfoWindow(marker) {
            let infoWindow = new AMap.InfoWindow({
                isCustom: true, //是否自定义信息窗体
                content: `<div style="background-color: white;padding: 0 5px; border-radius: 5px;border: 1px solid #cccccc;"> 地址：${this.address}</div>`,
                closeWhenClickMap: true,
                zIndex: 999,
                offset: new AMap.Pixel(16, -35),
            });
            infoWindow.open(this.map, marker.getPosition());
        },
    },
};
</script>
<style scoped lang="scss">
#mapContainer {
    width: 100%;
    height: 800px;
}
.mapRow {
    position: relative;
    .seachAddress {
        position: absolute;
        top: 10px;
        left: 10px;
        width: 450px;
    }
    .map_search_result {
        display: flex;
        flex-direction: column;
        border: 1px solid #dddddd;
        width: 450px;
        margin-top: 10px;
        background-color: #ffffff;
        position: absolute;
        top: 46px;
        left: 10px;
        .row {
            padding: 10px;
            border-top: 1px solid #dddddd;
            font-size: 14px;
            cursor: pointer;
        }
        .row:hover {
            background-color: #eeeeee;
        }
        .row:first-child {
            border-top: none;
        }
    }
}
</style>
